package com.blockmeta.bbs.immodule.activity;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import androidx.constraintlayout.widget.Group;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.adapter.CircleMembersAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.beaninterface.IFriendsEntry;
import com.blockmeta.bbs.immodule.bean.sort.GradeComparator;
import com.blockmeta.bbs.immodule.bean.sort.PinyinComparator;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.net.api.KickOutChatGroupApi;
import com.blockmeta.bbs.immodule.net.pojo.CircleMemberResponse;
import com.blockmeta.bbs.immodule.net.pojo.IMCircleEntityBook;
import com.blockmeta.bbs.immodule.utils.HanziToPinyin;
import com.blockmeta.bbs.immodule.widget.SideBar;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author airthor
 * @date 2019/3/19
 * 圈子成员
 */
public class CircleMembersActivity extends BaseActivity implements SideBar.OnTouchingLetterChangedListener, RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    public static final String SUFFIX = "_";
    @BindView(R2.id.fl_back)
    FrameLayout mFlBack;
    @BindView(R2.id.fl_cancel)
    FrameLayout mFlCancel;
    @BindView(R2.id.tv_title)
    TextView mTvTitle;
    @BindView(R2.id.tv_subtitle)
    TextView mTvSubtitle;
    @BindView(R2.id.fl_next)
    FrameLayout mFlNext;
    @BindView(R2.id.fl_sort)
    FrameLayout mFlSort;
    @BindView(R2.id.rcv_friends)
    RecyclerView mRcvFriends;
    @BindView(R2.id.group_dialog)
    TextView mGroupDialog;
    @BindView(R2.id.sidebar)
    SideBar mSidebar;
    @BindView(R2.id.title_container)
    View mSimpleTitle;
    @BindView(R2.id.group_search)
    Group mGroupSearch;
    @BindView(R2.id.edt_search_input)
    EditText mEdtSearchInput;
    @BindView(R2.id.rcv_search_list)
    RecyclerView mRcvSearchList;
    @BindView(R2.id.btn_kickoff)
    Button mBtnKickOff;

    private long mChatGroupId;
    private PopupWindow mPopupWindow;
    private List<IFriendsEntry> mFriendsEntries = new ArrayList<>();
    private List<IFriendsEntry> mFriendsEntriesForSearch = new ArrayList<>();
    public CircleMembersAdapter mMemberAdapter;
    public CircleMembersAdapter mMemberAdapterForSearch;
    private boolean mIsManger;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_circle_members, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        mSidebar.setOnTouchingLetterChangedListener(this);
        mBtnKickOff.bringToFront();
        mSidebar.bringToFront();
        mSidebar.setTextView(mGroupDialog);

        View header = getLayoutInflater().inflate(R.layout.header_search_circle_member, null);
        header.findViewById(R.id.ll_search_header).setOnClickListener(this);
        //圈子成员列表初始化
        mRcvFriends.setLayoutManager(new LinearLayoutManager(this));
        mMemberAdapter = new CircleMembersAdapter(R.layout.item_contacts_friends, mFriendsEntries, new CheckedListener());
        mMemberAdapter.addHeaderView(header);
        mMemberAdapter.bindToRecyclerView(mRcvFriends);
        //圈子成员搜索列表初始化
        mRcvSearchList.setLayoutManager(new LinearLayoutManager(this));
        mMemberAdapterForSearch = new CircleMembersAdapter(R.layout.item_contacts_friends, mFriendsEntriesForSearch, new CheckedListener());
        mMemberAdapterForSearch.bindToRecyclerView(mRcvSearchList);
        mMemberAdapterForSearch.groupByLetter(false);
        mRcvSearchList.bringToFront();
        //搜索框添加输入监听
        mEdtSearchInput.addTextChangedListener(new MyTextWatcher());

        netWork();
    }


    class CheckedListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            IFriendsEntry item = (IFriendsEntry) buttonView.getTag();
            item.setCheckedState(isChecked);

            int checkedCount = 0;
            for (IFriendsEntry entry :
                    mFriendsEntries) {
                if (entry.getCheckedState()) {
                    checkedCount++;
                }
            }
            mBtnKickOff.setText("移出圈子" + (checkedCount == 0 ? "" : String.format("(%s)", checkedCount + "")));

        }
    }

    @OnClick({R2.id.fl_back, R2.id.fl_cancel, R2.id.fl_next, R2.id.fl_sort, R2.id.tv_search_cancel, R2.id.btn_kickoff})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.fl_back) {
            finish();

        } else if (i == R.id.fl_cancel) {
            changeTitleBarState(false);

        } else if (i == R.id.fl_next) {
            changeTitleBarState(true);

        } else if (i == R.id.fl_sort) {
            showPopMenu();

        } else if (i == R.id.tv_search_cancel) {//取消搜索
            searching(false);

        } else if (i == R.id.btn_kickoff) {
            kickOffMember();
        } else {

        }

    }

    private void kickOffMember() {
        if (mChatGroupId == 0) {
            return;
        }
        StringBuilder stringBuilder = new StringBuilder("");
        final List<IFriendsEntry> kickOffMember = new ArrayList<>();
        for (IFriendsEntry entry :
                mFriendsEntries) {
            if (entry.getCheckedState()) {
                if (entry.getUserId() == AccountHelper.getUidInt()) {
                    ToastUtil.show("管理员不能踢出自己");
                    return;
                }
                stringBuilder.append(entry.getUserId()).append(SUFFIX);
                kickOffMember.add(entry);
            }
        }
        String kickWho = stringBuilder.toString();
        if (TextUtils.isEmpty(kickWho)) {
            ToastUtil.show("请先选择成员");
            return;
        }
        if (kickWho.endsWith(SUFFIX)) {
            kickWho = kickWho.substring(0, kickWho.length() - 1);
        }
        ProgressBarUtil.showProgress(mContext);
        RetrofitFactory.getRetrofit().create(KickOutChatGroupApi.class)
                .kickOutChatGroup(mChatGroupId, AccountHelper.getUidInt(), kickWho)
                .compose(RxUtil.<IMCircleEntityBook>commonResult())
                .compose(RxUtil.<IMCircleEntityBook>rxSchedulerHelper())
                .compose(((RxAppCompatActivity) mContext).<IMCircleEntityBook>bindToLifecycle())
                .subscribe(new CommonSubscriber<IMCircleEntityBook>(mContext) {
                    @Override
                    public void onNext(IMCircleEntityBook o) {
                        mFriendsEntries.removeAll(kickOffMember);
                        mFriendsEntriesForSearch.removeAll(kickOffMember);
                        mMemberAdapter.notifyDataSetChanged();
                        mMemberAdapterForSearch.notifyDataSetChanged();
                        IMApplicationContext.getIMMetaService().postSticky(new IMMetaBase.Event_KickOffMember(mChatGroupId, kickOffMember.size()));
                        ToastUtil.show("踢出成功！");
                    }
                });
    }

    private void changeTitleBarState(boolean editable) {
        mMemberAdapter.setEditable(editable);
        mMemberAdapterForSearch.setEditable(editable);
        mFlCancel.setVisibility(editable ? View.VISIBLE : View.GONE);
        mFlBack.setVisibility(editable ? View.GONE : View.VISIBLE);
        mFlNext.setVisibility(editable ? View.GONE : View.VISIBLE);
        mFlSort.setVisibility(editable ? View.VISIBLE : View.GONE);
        mBtnKickOff.setVisibility(editable ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        mMemberAdapter.scrollToTargetLetter(s);
    }

    private void netWork() {
        ArrayList<CircleMemberResponse> memberResponses = getIntent().getParcelableArrayListExtra(Params.MEMBERS);
        mIsManger = getIntent().getBooleanExtra(Params.ISMANGER, false);
        mFlNext.setVisibility(mIsManger ? View.VISIBLE : View.GONE);
        if (memberResponses == null) {
            return;
        }
        mChatGroupId = memberResponses.get(0).chatGroupId;
        for (CircleMemberResponse memberRespons : memberResponses) {
            IMUserEntity userEntity = IMApplicationContext.getUserDomainService().getUser(memberRespons.getUserId(), Params.USER_PERSON);
            String name = memberRespons.getName();
            if(userEntity != null){
                name = IMApplicationContext.getCircleDomainService()
                                .getCircleRemarkName(memberRespons.getUserId(), mChatGroupId, userEntity.getName(), userEntity.getRemarkName());
            }
            memberRespons.setName(name);
            memberRespons.setLetter(HanziToPinyin.getInstance().getLetter(name));
        }
        mFriendsEntries.addAll(memberResponses);
        Collections.sort(mFriendsEntries, new PinyinComparator());
        mMemberAdapter.notifyDataSetChanged();
    }

    /**
     * 弹出排序菜单
     */
    private void showPopMenu() {
        if (mPopupWindow == null) {
            View content = LayoutInflater.from(this).inflate(R.layout.pop_circle_member_sort, null);
            RadioGroup radioGroup = content.findViewById(R.id.radio_group);
            radioGroup.setOnCheckedChangeListener(this);

            mPopupWindow = new PopupWindow(content, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setTouchable(true);
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        }
        mPopupWindow.showAsDropDown(mSimpleTitle, 0, 0, Gravity.RIGHT | Gravity.BOTTOM);
    }

    /**
     * 排序菜单点击监听
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rd_default) {
            Collections.sort(mFriendsEntries, new PinyinComparator());
            mMemberAdapter.groupByLetter(true);
            mSidebar.setVisibility(View.VISIBLE);
            mMemberAdapter.notifyDataSetChanged();
            mPopupWindow.dismiss();

        } else if (checkedId == R.id.rd_to_high) {
            Collections.sort(mFriendsEntries, new GradeComparator(true));
            mMemberAdapter.groupByLetter(false);
            mSidebar.setVisibility(View.INVISIBLE);
            mMemberAdapter.notifyDataSetChanged();
            mPopupWindow.dismiss();

        } else if (checkedId == R.id.rd_to_low) {
            Collections.sort(mFriendsEntries, new GradeComparator(false));
            mMemberAdapter.groupByLetter(false);
            mSidebar.setVisibility(View.INVISIBLE);
            mMemberAdapter.notifyDataSetChanged();
            mPopupWindow.dismiss();

        } else {
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.ll_search_header) {
            searching(true);

        } else {
        }
    }

    /**
     * 开始搜索和结束搜索时UI的隐藏和展示
     *
     * @param isSearching true表示开始搜索 false结束搜索
     */
    private void searching(boolean isSearching) {
        mSimpleTitle.setVisibility(isSearching ? View.GONE : View.VISIBLE);
        mGroupSearch.setVisibility(isSearching ? View.VISIBLE : View.GONE);
        if (!isSearching) {
            mEdtSearchInput.setText("");
            mRcvSearchList.setVisibility(View.GONE);
            mFriendsEntriesForSearch.clear();
            mMemberAdapterForSearch.notifyDataSetChanged();
            mMemberAdapter.notifyDataSetChanged();
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputMethodManager != null) {
                inputMethodManager.hideSoftInputFromInputMethod(mEdtSearchInput.getWindowToken(), 0);
            }
        }
    }

    /**
     * 当处于搜索状态时 按返回键时先结束搜索状态
     */
    @Override
    public void onBackPressed() {
        if (mGroupSearch.isShown()) {
            searching(false);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 搜索输入监听
     */
    class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            getMatchedList(s.toString().trim());
        }
    }

    /**
     * 根据输入的字符串来获取匹配的成员列表
     *
     * @param pattern 输入的字符串
     */
    private void getMatchedList(String pattern) {
        mFriendsEntriesForSearch.clear();
        if (TextUtils.isEmpty(pattern)) {
            mRcvSearchList.setVisibility(View.GONE);
            mMemberAdapterForSearch.notifyDataSetChanged();
            return;
        }
        for (IFriendsEntry friendsEntry : mFriendsEntries) {
            if (friendsEntry.getName().toLowerCase().contains(pattern.toLowerCase())) {
                mFriendsEntriesForSearch.add(friendsEntry);
            }
        }
        mMemberAdapterForSearch.notifyDataSetChanged();
        mRcvSearchList.setVisibility(View.VISIBLE);
    }
}
